package com.cowin.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cowin.base.annotation.LogAnnotation;
import com.cowin.inf.model.KyWebLog;
import com.cowin.inf.service.KyWebLogService;
import com.cowin.utils.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * Copyright (C), 1998-2018, 奇瑞信息
 *
 * @author : 于超
 * @Date: 2019/9/3 11:58
 * @Description:
 */
@Slf4j
@Aspect
@Component
@Order(1)
public class WebLogAspect {

    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Resource
    private KyWebLogService kyWebLogService;

    @Pointcut("@annotation(com.cowin.base.annotation.LogAnnotation)")
    public void logPointCut() {
    }

    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
    }

    @AfterReturning(value = "logPointCut()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        //记录请求信息
        KyWebLog webLog = new KyWebLog();
        Object result = joinPoint.proceed();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method.isAnnotationPresent(LogAnnotation.class)) {
            LogAnnotation log = method.getAnnotation(LogAnnotation.class);
            webLog.setDescription(log.value());
        }
        long endTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            webLog.setBasePath(RequestUtil.getBasePath(request));
            webLog.setUserName(request.getRemoteUser());
            webLog.setIp(getRemoteHost(request));
            webLog.setMethod(request.getMethod());
            webLog.setUri(request.getRequestURI());
            webLog.setUrl(request.getRequestURL().toString());
        }
        webLog.setMethodName(((MethodSignature) signature).getMethod().getName());
        webLog.setSpendTime((int) (endTime - startTime.get()));
        webLog.setStartTime(DateFormatUtils.format(startTime.get(), "yyyy-MM-dd HH:mm:SSS"));
        webLog.setCreateTime(new Date());
        webLog.setResult(JSONObject.parseObject(result.toString()).get("code").toString());
        startTime.remove();
        log.info("{}----> 参数 = =  = {}---返回结果 = = = {}", webLog.getDescription(), JSON.toJSONString(getParameter(method, joinPoint.getArgs())), JSON.toJSONString(result));
//        rabbitTemplate.convertAndSend("webLogExchange", "webLogQueue", webLog);
        CompletableFuture.runAsync(() -> {
            try {
                kyWebLogService.save(webLog);
            } catch (Exception e2) {
                log.error(e2.getMessage());
            }
        });
        return result;
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }

    private String getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }
}
